package com.hzit.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.common.utils.AlipayTemplate;
import com.hzit.common.utils.IdWorker;
import com.hzit.common.utils.PayAsyncVo;
import com.hzit.common.utils.TbPayLog;
import com.hzit.order.dao.OrderDao;
import com.hzit.order.dao.OrderItemDao;
import com.hzit.order.dao.PayLogDao;
import com.hzit.order.entity.Cart;
import com.hzit.order.entity.TbAddress;
import com.hzit.order.entity.TbOrder;
import com.hzit.order.entity.TbOrderItem;
import com.hzit.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.swing.StringUIClientPropertyKey;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, TbOrder> implements OrderService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private IdWorker idWorker;
	@Autowired
	private OrderItemDao itemDao;
	@Autowired
	private PayLogDao payLogDao;
	@Autowired
	private AlipayTemplate alipayTemplate;


	//1. 根据登录名查询购物车列表
	@Override
	public List<Cart> findCartList(String name) {
		//1.1 得到购物车列表
		String cartList = (String) redisTemplate.opsForHash().get("cartList", name);
		//1.2 判断是否有值
		if(StrUtil.isNotBlank(cartList)){
			return JSON.parseArray(cartList,Cart.class);
		}
		return new ArrayList<>();
	}

	//2. 添加到订单及订单项
	@Override
	@Transactional
	public void add(String name,TbOrder tbOrder) {
		//2.1 得到当前登录用户的购物车列表
		List<Cart> cartList = findCartList(name);
		//2.2 遍历购物车列表
		//2.2.1 定义订单总金额
		double total = 0;    // 代表总有订单的总金额
		// 定义存放订单号的集合
		List<String> ids = new ArrayList<>();
		for (Cart cart : cartList) {
			double sum = 0;
			//2.3 定义要添加的订单对象
			TbOrder order = new TbOrder();
			long id = idWorker.nextId();
			ids.add(id + "");
			order.setOrderId(id);
			order.setCreateTime(new Date());
			order.setPaymentType(tbOrder.getPaymentType()); // 支付类型
			order.setStatus("1");                           // 未付款
			order.setReceiver(tbOrder.getReceiver());       // 联系人
			order.setReceiverAreaName(tbOrder.getReceiverAreaName()); // 住址
			order.setReceiverMobile(tbOrder.getReceiverMobile());     // 手机号
			order.setSellerId(cart.getSellerId());
			order.setUpdateTime(new Date());
			order.setUserId(name);

			//2.4 处理订单项
			for (TbOrderItem orderItem : cart.getOrderItemList()) {
				long orderItemId = idWorker.nextId();
				orderItem.setId(orderItemId);
				orderItem.setOrderId(id);
				//累加小计
				sum += orderItem.getTotalFee().doubleValue();
				//开始添加
				itemDao.insert(orderItem);
			}
			//为订单设置总金额
			order.setPayment(new BigDecimal(sum));
			total += sum;
			// 添加订单
			this.save(order);
		}

		//todo... 添加数据到支付日志中
		if (tbOrder.getPaymentType().equals("1")) {
			//1.1 构造支付日志对象
			TbPayLog log = new TbPayLog();
			log.setCreateTime(new Date());
			log.setOutTradeNo(idWorker.nextId() + "");
			log.setPayType("1");
			log.setTotalFee((long)(total * 100));
			log.setUserId(name);
			log.setTradeState("0");     // 代表未支付
			String idStr = ids.toString().replace("[", "").replace("]", "");
			log.setOrderList(idStr);    // 设置订单编号
			//1.2 添加日志到数据库
			payLogDao.insert(log);

			//1.3 将支付日志对象保存到redis中
			redisTemplate.opsForValue().set(name + "_payLog",JSON.toJSONString(log));
		}

		//todo: 删除购物车
	}

	//3. 保存订单 (分支事务)
	@Override
	@Transactional
	public void saveOrder() {
		TbOrder order = new TbOrder();
		order.setUserId("zhangsan");
		order.setStatus("1");
		this.save(order);
		int i = 10 / 0;
	}

	//4. 生成支付页面
	@Override
	public String createPayPage(String outTradeNo, String totalFee) throws AlipayApiException {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(alipayTemplate.getGatewayUrl(),
				alipayTemplate.getApp_id(), alipayTemplate.getMerchant_private_key(),
				"json", alipayTemplate.getCharset(),
				alipayTemplate.getAlipay_public_key(), alipayTemplate.getSign_type());

		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(alipayTemplate.getReturn_url());
		alipayRequest.setNotifyUrl(alipayTemplate.getNotify_url());

		//商户订单号，商户网站订单系统中唯一订单号，必填
		// String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		// //付款金额，必填
		// String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
		// //订单名称，必填
		// String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
		// //商品描述，可空
		// String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

		alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
				+ "\"total_amount\":\""+ totalFee +"\","
				+ "\"subject\":\""+ alipayTemplate.getSubject() +"\","
				+ "\"body\":\""+ alipayTemplate.getBody() +"\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

		//若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
		//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
		//		+ "\"total_amount\":\""+ total_amount +"\","
		//		+ "\"subject\":\""+ subject +"\","
		//		+ "\"body\":\""+ body +"\","
		//		+ "\"timeout_express\":\"10m\","
		//		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

		//请求
		String result = alipayClient.pageExecute(alipayRequest).getBody();

		//输出
		// out.println(result);
		return result;
	}

	//2. 发送异步通知
	@Override
	public String sendNotify(Map<String, String[]> requestParams, PayAsyncVo vo) throws UnsupportedEncodingException, AlipayApiException {
		//2.1 将得到的数据转换为Map<String,String>， 便于后面验签
		Map<String,String> params = new HashMap<String,String>();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		//2.2 进行异步验签
		boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
		//2.3 如果验签通过，就接着执行我们自己的业务逻辑
		if(signVerified){
			//2.3.1  如果支付状态值是TRADE_SUCCESS或TRADE_FINISHED,代表异步请求成功，接着执行我们自己的业务
			if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
				System.out.println("做自己的事。。");
				return "success";
			}
		}

		return "fail";
	}

	//3. 根据用户名得到订单及订单项列表
	@Override
	public List<TbOrder> findOrderListByname(String name) {
		//3.1 根据用户名查询到订单列表
		List<TbOrder> orderList = this.list(new QueryWrapper<TbOrder>().eq("user_id", name));
		//3.2 遍历订单列表，关联订单项列表
		for (TbOrder order : orderList) {
			//3.2.1 查询某个订单关联的订单项列表
			List<TbOrderItem> orderItems = itemDao.selectList(new QueryWrapper<TbOrderItem>().eq("order_id", order.getOrderId()));
			//3.2.2 将其与订单绑定
			order.setOrderItems(orderItems);
		}
		return orderList;
	}
}
